package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.dto.SearchParamDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.entity.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.index.Term;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import java.util.*;
import java.util.stream.Collectors;

import static com.leyou.search.constants.SearchConstants.*;

//import static org.elasticsearch.search.builder.SearchSourceBuilder.SUGGEST_FIELD;

/**
 * @author BaiZY on 2020/8/30.
 * @version 1.0
 */
@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    private final GoodsRepository goodsRepository;

    private final ItemClient itemClient;

    public SearchServiceImpl(GoodsRepository goodsRepository, ItemClient itemClient) {
        this.goodsRepository = goodsRepository;
        this.itemClient = itemClient;
    }

    @Override
    public void createIndexAndMapping() {
        //删除已经存在的索引库
        try {
            goodsRepository.deleteIndex();
        } catch (Exception e) {
            log.info("删除失败,索引库可能不存在!", e);
        }

        goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");

    }

    @Override
    public void loadData() {
        int page = 1, rows = 100;
        while (true) {
            log.info("开始导入第{}页的数据", page);
            //分页查询已经上架的spu
            PageDTO<SpuDTO> result = itemClient.querySpuByPage(page, rows, true, null, null, null);
            List<SpuDTO> list = result.getItems();
            // 遍历Spu集合，把SpuDTO通过buildGoods方法转为Goods
            List<Goods> goodsList = list.stream().map(this::buildGoods).collect(Collectors.toList());

            // 批量写入Elasticsearch
            goodsRepository.saveAll(goodsList);
            log.info("导入第{}页数据结束", page);

            //翻页
            page++;

            //获取总页数
            Long totalPage = result.getTotalPage();

            // 判断是否还有spu没有查询
            if (page > totalPage) {
                break;
            }
        }
    }

    @Override
    public Mono<List<String>> getSuggestion(String keyPrefix) {
        if (StringUtils.isBlank(keyPrefix)) {
            throw new LyException(400, "请求参数不能为空");
        }
        return goodsRepository.suggestBySingleField(SUGGESTION_FIELD, keyPrefix);
    }

    @Override
    public Mono<PageInfo<Goods>> searchGoods(SearchParamDTO searchParamDTO) {
        //构建查询条件的工厂对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //source过滤
        sourceBuilder.fetchSource(DEFAULT_SOURCE_FIELD, new String[0]);

        //获取查询条件封装对象
        QueryBuilder query = builderQuery(searchParamDTO);

        sourceBuilder.query(query);

        //添加查询条件
        sourceBuilder.query(query);

        //分页条件
        sourceBuilder.from(searchParamDTO.getFrom());
        sourceBuilder.size(searchParamDTO.getSize());

        //排序条件
        if (StringUtils.isNotBlank(searchParamDTO.getSortBy())) {
            sourceBuilder.sort(searchParamDTO.getSortBy(), searchParamDTO.getDesc() ? SortOrder.DESC : SortOrder.ASC);
        }

        //高亮条件
        sourceBuilder.highlighter(new HighlightBuilder().field(DEFAULT_SEARCH_FIELD).preTags(DEFAULT_PRE_TAG).postTags(DEFAULT_POST_TAG));


        Mono<PageInfo<Goods>> pageInfoMono = goodsRepository.queryBySourceBuilderForPageHighlight(sourceBuilder);
        return pageInfoMono;
    }

    @Override
    public void saveGoodsById(Long spuId) {
        PageDTO<SpuDTO> spuPage = itemClient.querySpuByPage(1, 1, true, null, null, spuId);
        List<SpuDTO> spuDTOs = spuPage.getItems();
        Goods goods = buildGoods(spuDTOs.get(0));
        goodsRepository.save(goods);
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        goodsRepository.deleteById(spuId);
    }

    @Override
    public Mono<Map<String, List<?>>> listFilter(SearchParamDTO searchParamDTO) {

        //创建查询条件构造器
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //添加查询条件
        sourceBuilder.query(builderQuery(searchParamDTO));

        //对品牌聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("brandAgg").field("brandId"));

        //对分类聚合
        sourceBuilder.aggregation(AggregationBuilders.terms("categoryAgg").field("categoryId"));

        //对规格参数进行聚合
        sourceBuilder.aggregation(AggregationBuilders.nested("specAgg", "specs")
                .subAggregation(AggregationBuilders.terms("nameAgg").field("specs.name")
                        .subAggregation(AggregationBuilders.terms("valueAgg").field("specs.value"))));

        //查询聚合
        Mono<Aggregations> aggregationsMono = goodsRepository.aggregationBySourceBuilder(sourceBuilder);

        //解析聚合
        return aggregationsMono.map(aggregations -> {
            Map<String, List<?>> result = new LinkedHashMap<>();
            Terms categoryAgg = aggregations.get("categoryAgg");

            List<Long> categoryIds = categoryAgg.getBuckets()
                    .stream()
                    .map(Terms.Bucket::getKeyAsNumber)
                    .map(Number::longValue)
                    .collect(Collectors.toList());
            //判断id集合是否为空
            if (CollectionUtils.isEmpty(categoryIds)) {
                result.put("分类", new ArrayList<>());
            } else {
                result.put("分类", itemClient.queryCategoryByIds(categoryIds));
            }

            Terms brandAgg = aggregations.get("brandAgg");

            List<Long> brandIds = brandAgg.getBuckets()
                    .stream()
                    .map(Terms.Bucket::getKeyAsNumber)
                    .map(Number::longValue)
                    .collect(Collectors.toList());
            //判断brandIds集合是否为空
            if (CollectionUtils.isEmpty(brandIds)) {
                result.put("品牌", new ArrayList<>());
            } else {
                result.put("品牌", itemClient.queryBrandByIds(brandIds));
            }

            //获取规格参数的nested聚合
            Nested specAgg = aggregations.get("specAgg");

            //从nested聚合中获取nameAgg聚合
            Terms nameAgg = specAgg.getAggregations().get("nameAgg");

            //获取其聚合内容
            nameAgg.getBuckets()
                    .stream()
                    .forEach(bucket -> {
                        //获取聚合的key
                        String key = ((Terms.Bucket) bucket).getKeyAsString();
                        Terms valueAgg = ((Terms.Bucket) bucket).getAggregations().get("valueAgg");

                        //从子聚合中获取聚合结果
                        List<String> values = valueAgg.getBuckets()
                                .stream()
                                .map(Terms.Bucket::getKeyAsString)
                                .collect(Collectors.toList());
                        result.put(key, values);
                    });

            return result;

        });
    }

    private QueryBuilder builderQuery(SearchParamDTO searchParamDTO) {
        String key = searchParamDTO.getKey();
        //数据校验处理
        if (StringUtils.isEmpty(key)) {
            throw new LyException(400, "请求参数封装有误,查询key不能为空");
        }
        Integer page = searchParamDTO.getPage();
        if (page == null || page < 1) {
            page = 1;
        }

        return QueryBuilders.matchQuery("title", key).operator(Operator.AND);
    }

    private Goods buildGoods(SpuDTO spuDTO) {
        //1.自动补全字段提示
        List<String> suggestion = new ArrayList<>(
                Arrays.asList(StringUtils.split(spuDTO.getCategoryName(), "/")));
        suggestion.add(spuDTO.getName());
        suggestion.add(spuDTO.getBrandName());

        //2.sku的价格集合
        //2.1查询sku集合
        List<SkuDTO> skuList = spuDTO.getSkus();
        if (CollectionUtils.isEmpty(skuList)) {
            //没有sku,我们去查询
            skuList = itemClient.querySkuBySpuId(spuDTO.getId());
        }

        //2.2 获取价格集合
        Set<Long> prices = skuList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());

        //3. 商品销量
        long sold = skuList.stream().mapToLong(SkuDTO::getSold).sum();

        //4. sku的某个图片
        String image = StringUtils.substringBefore(skuList.get(0).getImages(), ",");

        //5.规格参数
        List<Map<String, Object>> specs = new ArrayList<>();
        //5.1 查询规格参数name和value键值对,只查询参与搜索的
        List<SpecParamDTO> params = itemClient.querySpecsValues(spuDTO.getId(), true);
        //5.2 封装
        for (SpecParamDTO param : params) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("name", param.getName());
            map.put("value", chooseSegment(param));
            specs.add(map);
        }

        //创建Goods对象
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        //自动补全的提示字段
        goods.setSuggestion(suggestion);
        //规格参数
        goods.setSpecs(specs);
        //商品销量
        goods.setSold(sold);
        //商品标题
        goods.setTitle(spuDTO.getTitle() + StringUtils.join(suggestion, " "));

        //sku的价格集合
        goods.setPrices(prices);
        //sku的某个图片
        goods.setImage(image);
        goods.setCategoryId(spuDTO.getCid3());
        goods.setBrandId(spuDTO.getBrandId());
        goods.setId(spuDTO.getId());

        return goods;
    }

    private Object chooseSegment(SpecParamDTO param) {
        Object value = param.getValue();

        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }

        if (!param.getNumeric() || StringUtils.isBlank(param.getSegments()) || value instanceof Collection) {
            return value;
        }

        double val = parseDouble(value.toString());
        String result = "其它";

        //保存数值段
        for (String segment : param.getSegments().split(",")) {
            String[] segs = segment.split("-");
            //获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }

            //判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + param.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + param.getUnit() + "以下";
                } else {
                    result = segment + param.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

}
